<template>
  <div style="height: 10vh; background-color: #fff; padding: 10px 20px;">
    <el-card style="height: 100%;">
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="停车场：" prop="parkName">
          <el-select v-model="searchForm.parkName" placeholder="请选择停车场" style="width: 15vh;" filterable clearable>
            <el-option v-for="park in parklotOptions" :key="park.value" :label="park.label" :value="park.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号：" prop="carCode">
          <el-select v-model="searchForm.carCode" placeholder="请选择车牌号" style="width: 15vh;" filterable clearable>
            <el-option v-for="record in carCodeOptions" :key="record.value" :label="record.label" :value="record.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="进场时间：" prop="entryTime">
          <el-date-picker
              v-model="searchForm.entryTime"
              type="datetime"
              placeholder="选择进场时间"
              style="width: 20vh;"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="离场时间：" prop="leaveTime">
          <el-date-picker
              v-model="searchForm.leaveTime"
              type="datetime"
              placeholder="选择离场时间"
              style="width: 20vh;"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <el-form :inline="true">
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" :loading="loading" @click="queryForm">查询</el-button>
          <el-button type="primary" @click="openDialog('create')">新建</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40vh" @close="resetDialogForm">
    <el-form label-width="8vh" label-position="left" :model="dialogForm" :rules="dialogRules" ref="dialogFormRef">
      <el-form-item label="停车场" prop="parkName">
        <el-select v-model="dialogForm.parkName" placeholder="请选择停车场" style="width: 100%;" filterable>
          <el-option v-for="park in parklotOptions" :key="park.value" :label="park.label" :value="park.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="车牌号" prop="carCode">
        <el-input v-model="dialogForm.carCode" placeholder="请输入车牌号" />
      </el-form-item>
      <el-form-item label="停车类型" prop="parkType">
        <el-select v-model="dialogForm.parkType" placeholder="请选择停车类型" style="width: 100%;">
          <el-option label="临停车" value="临停车" />
          <el-option label="月租车" value="月租车" />
        </el-select>
      </el-form-item>
      <el-form-item label="计费规则" prop="billRule" v-if="dialogForm.parkType === '临停车'">
        <el-select v-model="dialogForm.billRule" placeholder="请选择计费规则" style="width: 100%;" filterable>
          <el-option v-for="rule in billRuleOptions" :key="rule.value" :label="rule.label" :value="rule.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="进场时间" prop="entryTime">
        <el-date-picker
            v-model="dialogForm.entryTime"
            type="datetime"
            placeholder="选择进场时间"
            style="width: 100%;"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="离场时间" prop="leaveTime">
        <el-date-picker
            v-model="dialogForm.leaveTime"
            type="datetime"
            placeholder="选择离场时间"
            style="width: 100%;"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" :loading="saving" @click="saveDialog">确定</el-button>
    </template>
  </el-dialog>

  <!-- 停车记录列表和分页区域 -->
  <el-card style="margin: 20px; height: 70vh; display: flex; flex-direction: column;">
    <div class="table-container">
      <el-table
          :data="recordList"
          border
          v-loading="loading"
          @selection-change="handleSelectionChange"
          ref="tableRef"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="parkName" label="停车场" align="center" />
        <el-table-column prop="carCode" label="车牌号" align="center" />
        <el-table-column prop="parkType" label="停车类型" align="center" />
        <el-table-column prop="billRule" label="计费规则" align="center" />
        <el-table-column prop="entryTime" label="进场时间" align="center" />
        <el-table-column prop="leaveTime" label="离场时间" align="center" />
        <el-table-column prop="duration" label="停车时长" align="center">
          <template #default="scope">
            {{ formatDuration(scope.row.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="predictFee" label="预计费用" align="center">
          <template #default="scope">
            {{ formatFee(scope.row.predictFee) }}
          </template>
        </el-table-column>
        <el-table-column prop="isBlacklist" label="是否黑名单" align="center" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const API_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:9999';

// 数据列表和加载状态
const parklotOptions = ref([]);
const carCodeOptions = ref([]);
const billRuleOptions = ref([]);
const recordList = ref([]);

// 分页相关
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索表单数据
const searchFormRef = ref(null);
const searchForm = ref({});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const dialogForm = ref({
  id: null,
  parkName: '',
  carCode: '',
  parkType: '临停车',
  billRule: '',
  entryTime: '',
  leaveTime: ''
});
const dialogRules = ref({
  parkName: [{ required: true, message: '请选择停车场', trigger: 'change' }],
  carCode: [
    { required: true, message: '请输入车牌号', trigger: 'blur' },
    { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](?:[A-HJ-NP-Z0-9]{5}|[DF][A-HJ-NP-Z0-9]{5})$/, message: '请输入合法车牌号', trigger: 'blur' }
  ],
  parkType: [{ required: true, message: '请选择停车类型', trigger: 'change' }],
  billRule: [{ required: true, message: '请选择计费规则', trigger: 'change', validator: (rule, value, callback) => {
      if (dialogForm.value.parkType === '临停车' && !value) {
        callback(new Error('请选择计费规则'));
      } else {
        callback();
      }
    }}],
  entryTime: [{ required: true, message: '请选择进场时间', trigger: 'change' }]
});
const dialogFormRef = ref(null);
const saving = ref(false);

// 多选框相关
const selectedRows = ref([]);
const tableRef = ref(null);

// 重置搜索表单
const resetForm = () => {
  searchFormRef.value.resetFields();
  currentPage.value = 1;
  queryForm();
};

// 查询搜索表单
const queryForm = () => {
  fetchParkingRecords();
};

const formatDuration = (minutes) => {
  if (!minutes || minutes < 0) return '0分钟';
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  if (hours > 0) {
    return `${hours}小时${remainingMinutes}分钟`;
  }
  return `${remainingMinutes}分钟`;
};

const formatFee = (fee) => {
  if (fee === null || fee === undefined) return '¥0.00';
  return `¥${fee.toFixed(2)}`;
};

// 获取停车记录列表
const fetchParkingRecords = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm.value,
      page: currentPage.value,
      size: pageSize.value
    };
    const { data } = await axios.get(`${API_URL}/v1/parkRecord/select`, { params });
    console.log('查询停车记录响应:', data);
    if (data.code === 2000) {
      recordList.value = data.response || [];
      total.value = data.total || 0;
      updateCarCodeOptions(data.response);
    } else {
      ElMessage.error(`获取停车记录失败: ${data.response || '未知错误'}`);
      recordList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取停车记录失败:', error.response || error);
    ElMessage.error('获取停车记录失败，请检查网络或后端服务');
    recordList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取停车场列表
const fetchParklotOptions = async () => {
  try {
    const { data } = await axios.get(`${API_URL}/v1/parklot/select`, { params: { size: 10000 } });
    console.log('查询停车场选项响应:', data);
    if (data.code === 2000) {
      parklotOptions.value = data.response.map(park => ({
        value: park.parkName,
        label: park.parkName
      }));
    } else {
      ElMessage.error(`获取停车场列表失败: ${data.response || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取停车场列表失败:', error.response || error);
    ElMessage.error('获取停车场列表失败，请检查网络或后端服务');
  }
};

// 获取计费规则列表
const fetchBillRuleOptions = async () => {
  try {
    const { data } = await axios.get(`${API_URL}/v1/bill-temp-rule/select`, { params: { size: 10000 } });
    console.log('查询计费规则响应:', data);
    if (data.code === 2000) {
      billRuleOptions.value = [
        { value: '免费停车', label: '免费停车' },
        ...data.response.map(rule => ({
          value: rule.ruleName,
          label: rule.ruleName
        }))
      ];
    } else {
      ElMessage.error(`获取计费规则失败: ${data.response || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取计费规则失败:', error.response || error);
    ElMessage.error('获取计费规则失败，请检查网络或后端服务');
  }
};

// 更新车牌号选项
const updateCarCodeOptions = (records) => {
  carCodeOptions.value = [...new Set(records.map(record => record.carCode))].map(carCode => ({
    value: carCode,
    label: carCode
  }));
};

// 打开弹窗
const openDialog = (type, row = {}) => {
  dialogVisible.value = true;
  dialogTitle.value = type === 'create' ? '新建停车记录' : '编辑停车记录';
  dialogForm.value = type === 'create'
      ? { id: null, parkName: '', carCode: '', parkType: '临停车', billRule: '', entryTime: '', leaveTime: '' }
      : { ...row };
};

// 重置弹窗表单
const resetDialogForm = () => {
  if (dialogFormRef.value) {
    dialogFormRef.value.resetFields();
  }
  dialogForm.value = {
    id: null,
    parkName: '',
    carCode: '',
    parkType: '临停车',
    billRule: '',
    entryTime: '',
    leaveTime: ''
  };
};

// 关闭弹窗
const closeDialog = () => {
  ElMessageBox.confirm('您确认要关闭本弹窗吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        dialogVisible.value = false;
      })
      .catch(() => {});
};

// 保存弹窗数据
const saveDialog = async () => {
  try {
    await dialogFormRef.value.validate((valid) => {
      if (!valid) throw new Error('表单验证失败，请检查输入');
    });
    saving.value = true;
    const saveData = {
      id: dialogForm.value.id,
      parkName: dialogForm.value.parkName || null,
      carCode: dialogForm.value.carCode || null,
      parkType: dialogForm.value.parkType || null,
      billRule: dialogForm.value.parkType === '临停车' ? dialogForm.value.billRule : null,
      entryTime: dialogForm.value.entryTime || null,
      leaveTime: dialogForm.value.leaveTime || null
    };
    if (!saveData.parkName) throw new Error('停车场名称不能为空');
    if (!saveData.carCode) throw new Error('车牌号不能为空');
    if (!saveData.entryTime) throw new Error('进场时间不能为空');
    if (!saveData.parkType) throw new Error('停车类型不能为空');
    if (saveData.parkType === '临停车' && !saveData.billRule) throw new Error('计费规则不能为空');
    const url = `${API_URL}/v1/parkRecord/save`;
    console.log('发送的保存数据:', saveData);
    const { data } = await axios.post(url, saveData);
    console.log('保存停车记录响应:', data);
    if (data.code === 2000) {
      ElMessage.success('保存成功');
      dialogVisible.value = false;
      await fetchParkingRecords();
    } else {
      throw new Error(data.response || '未知错误');
    }
  } catch (error) {
    console.error('保存停车记录失败:', error.response || error);
    ElMessage.error(`保存失败: ${error.response?.data?.response || error.message || '请检查网络或后端服务'}`);
  } finally {
    saving.value = false;
  }
};

// 处理多选框变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 分页事件处理
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchParkingRecords();
};

// 初始化数据
onMounted(async () => {
  await fetchParklotOptions();
  await fetchBillRuleOptions();
  await fetchParkingRecords();
});
</script>

<style scoped>
.table-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px;
}

.pagination-container {
  padding: 10px 20px;
  text-align: center;
  background-color: #fff;
  min-height: 60px;
}
</style>